/**
 * 异步请求
 *
 */
import _ from 'lodash';
import axios from './axios';
import { Toast, Indicator } from 'mint-ui';
import config from '../base/profile/config.json';
/*
{
    url:"",  //api
    type:"get"
    data:{}   //data
    suffixParams:""  //url上参数
}
*/
export default function (params) {
    // debugger
    // 过滤掉参数中的前后空格
    let paramsObj = {
        controlLoading: true
    };
    _.assignWith(paramsObj, params);
    if (paramsObj.controlLoading) {
        Indicator.open({
            text: '加载中...',
            spinnerType: 'fading-circle'
        });
    }
    //是否为公司内网远程调试
    var isH5Debug = location && location.href && location.href.startsWith("http://10.");
    let url = _.trimEnd(_.trim(paramsObj.url)) + (paramsObj.suffixParams ? _.trim(paramsObj.suffixParams) : '');
    if(url.startsWith('/')){
        url = url.replace(new RegExp('^\\'+'/'+'+', 'g'), '');
    }
    if((/cross-bm/i.test(navigator.userAgent))&& !isH5Debug){
        url = window.APP.serverUrl + url;
    }
    //let callApi = { url: url,data:paramsObj, timerId: new Date().getTime(), hasDone: false };
    if ((/cross-bm/i.test(navigator.userAgent)) && (params.type && params.type.toUpperCase() == 'POST') && !isH5Debug) {
        return new Promise(function (resolve, reject) {
            //AppUtil.call2(AppUtil.APIS.WRITE_LOG_TO_APP,{text:"web****SEND_HTTP_REQUEST****param="+JSON.stringify(callApi)});
            AppUtil.call(AppUtil.APIS.SEND_HTTP_REQUEST,
                {
                    type: "POST",
                    url: url,
                    data: JSON.stringify(paramsObj.data)
                }, function (result) {
                    if (paramsObj.controlLoading) {
                        Indicator.close();
                    }
                    resolve(result);
                });
        }).then((result) => {
            //AppUtil.call2(AppUtil.APIS.WRITE_LOG_TO_APP,{text:"web****SEND_HTTP_REQUEST****"+callApi.url+"****result="+JSON.stringify(result)});
            if (paramsObj.controlLoading) {
                Indicator.close();
            }
            let response = result.resultObject;
            let status = {};

            if (response) {
                let code = parseInt(response.code);
                switch (code) {

                    case 302://登陆

                    /**
                     * 权限
                     */
                    case 444:
                    case 404:
                    case 406:

                    /**
                     * 错误信息
                     */
                    case 410:
                    case 500:
                    case 503:
                    case 512:
                    case 513:
                    case 514:
                    case 998:
                        status = { status: code, message: response.msg };
                        var err = new Error(status.message);
                        err.data = response.data;
                        err.response = status;
                        break;
                    default:
                        return response;
                }
                return reject({
                    response: status
                });
            }
        }).catch((error) => {
            //AppUtil.call2(AppUtil.APIS.WRITE_LOG_TO_APP,{text:"web****SEND_HTTP_REQUEST****"+callApi.url+"****error="+JSON.stringify(error)});
            Indicator.close();
            let msg = '';
            if (typeof error.response === 'undefined') {
                msg = '无法连接网络，请检查网络设置后重试。';
            }
            else if (error.response.status === 500 || error.response.status === 502) {
                msg = !error.response.message || error.response.message == '' ? '服务器错误，请稍后重试' : error.response.message;
            } else if (error.response.status === 302) {
                msg = error.response.message;
                if ((/cross-bm/i.test(navigator.userAgent))) {
                    localStorage.clear();
                    AppUtil.call(AppUtil.APIS.LOGIN);
                }
            } else if (error.response.status === 504) {
                msg = !error.response.message || error.response.message == '' ? '504,服务器错误，请稍后重试' : error.response.message;
            } else if (error.response.status === 404) {
                msg = !error.response.message || error.response.message == '' ? '404，接口未找到，请稍后重试' : error.response.message;
            }
            else {
                msg = error.response.message;
            }
            if (typeof msg !== 'string') {
                msg = _.values(msg).join('；');
            }

            Toast({
                message: msg,
                duration: 3000
            });

            throw new Error(error);
        });

    } else {
        if (paramsObj.type && paramsObj.type.toUpperCase() == "GET") {
            if (url.indexOf("?") !== -1) {
                url += "&sessionId=" + window.APP.sessionId;
            } else {
                url += "?sessionId=" + window.APP.sessionId;

            }
            if (paramsObj.data) {
                url += '&' + window.CommonUtil.parseParam(paramsObj.data);
            }
        }
       // AppUtil.call2(AppUtil.APIS.WRITE_LOG_TO_APP,{text:"web****axios****param="+JSON.stringify(callApi)});
        return axios({
            url: url,
            timeout: paramsObj.timeout || 10000,
            method: paramsObj.type,
            data: paramsObj.data,
            responseType: 'json',
            headers: {
                'Accept': 'application/json',
                'sessionId': window.APP.sessionId,
                'Content-Type': 'application/json'
            }
        })
            .then(function (response) {
                //AppUtil.call2(AppUtil.APIS.WRITE_LOG_TO_APP,{text:"web****axios****"+callApi.url+"****result="+JSON.stringify(response)});
                if (paramsObj.controlLoading) {
                    Indicator.close();
                }
                let status = {};
                let code = parseInt(response.data.code);
                switch (code) {

                    case 302://登陆

                    /**
                     * 权限
                     */
                    case 444:
                    case 404:
                    case 406:

                    /**
                     * 错误信息
                     */
                    case 410:
                    case 500:
                    case 503:
                    case 512:
                    case 513:
                    case 514:
                    case 998:
                        status = { status: code, message: response.data.msg };
                        var err = new Error(status.message);
                        err.data = response.data;
                        err.response = status;
                        throw err
                        break;
                    default:
                        return response.data;
                }
            })
            .catch((error) => {
                //AppUtil.call2(AppUtil.APIS.WRITE_LOG_TO_APP,{text:"web****axios****"+callApi.url+"****error="+JSON.stringify(error)});
                Indicator.close();
                let msg = '';
                if (typeof error.response === 'undefined') {
                    msg = '无法连接网络，请检查网络设置后重试。';
                }
                else if (error.response.status === 500 || error.response.status === 502|| error.response.status === 503) {
                    msg = !error.response.message || error.response.message == '' ? '服务器错误，请稍后重试' : error.response.message;
                } else if (error.response.status === 302) {
                    msg = error.response.message;
                    if ((/cross-bm/i.test(navigator.userAgent))) {
                        localStorage.clear();
                        AppUtil.call(AppUtil.APIS.LOGIN);
                    }
                } else if (error.response.status === 504) {
                    msg = !error.response.message || error.response.message == '' ? '504,服务器错误，请稍后重试' : error.response.message;
                } else if (error.response.status === 404) {
                    msg = !error.response.message || error.response.message == '' ? '404，接口未找到，请稍后重试' : error.response.message;
                }
                else {
                    msg = error.response.message;
                }
                if (typeof msg !== 'string') {
                    msg = _.values(msg).join('；');
                }

                Toast({
                    message: msg,
                    duration: 3000
                });
                return Promise.reject({
                    response:error
                });
                //throw new Error(error);
            });
    };
}
